package net.lzzy.practices.web.models;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import net.lzzy.practices.constants.ApiConstant;
import net.lzzy.practices.constants.Massages;
import net.lzzy.practices.entities.User;
import net.lzzy.practices.services.UserService;
import net.lzzy.practices.utils.FileUtil;
import net.lzzy.practices.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author admin
 */
@Api(tags = "用户认证")
@RestController
@RequestMapping(ApiConstant.ROUTE_AUTH_ROOT)
public class AuthApiController {
    private  final UserService service;


    @Autowired
    public AuthApiController(UserService service) {
        this.service = service;
    }
    @ApiOperation("登录")
    @ApiImplicitParam(name = "info",value = "用户登录信息",dataType = "LoginInfo",dataTypeClass = LoginInfo.class,
            paramType = "body",required = true)
    @PostMapping(value = ApiConstant.ROUTE_AUTH_LOGIN, produces = ApiConstant.API_PRODUCES)
    public ApiResult login(@RequestBody LoginInfo info) {
        String username = info.getUsername();
        String password = info.getPassword();
        String salt = service.getSalt(username);
        User user = service.check(username, StringUtil.md5Encode(password, salt));
        if (user == null) {
            return new ApiResult(false, Massages.WRONG_PASSWORD.toString(), null);
        }
        if (user.getType() < 0) {
            return new ApiResult(false, Massages.NO_PERMISSION.toString(), null);
        }
        VmUser vmUser = VmUser.apiLogin(user);
        return new ApiResult(true, Massages.SUCCESS.toString(), vmUser);
    }
    @ApiOperation("判断用户名是否存在")
    @ApiImplicitParam(name = "user",value = "用户名",dataType = "String",dataTypeClass = String.class,
            paramType = "path",required = true)
    @GetMapping(ApiConstant.ROUTE_AUTH_EXISTS)
    public ApiResult IsUserExists(@PathVariable String user){
        boolean exists=service.isUserNameOccupied(user);
        return new ApiResult(true,exists ?"用户已存在":"",exists);
    }
    @ApiOperation("注册新用户")
    @ApiImplicitParam(name = "info",value = "注册信息",dataType = "RegisterInfo",dataTypeClass = RegisterInfo.class,
            paramType = "body",required = true)
    @PostMapping(value = ApiConstant.ROUTE_AUTH_REGISTER,produces = ApiConstant.API_PRODUCES)
    public  ApiResult register(@RequestBody RegisterInfo info){
        String nick= info.getNick();
        String user= info.getUser();
        String phone= info.getPhone();
        String email= info.getEmail();
        String password= info.getPwd();
        String avatar= info.getAvatar();
        boolean teacher= info.isTeacher();
        String salt= UUID.randomUUID().toString();
        if (StringUtil.isEmpty(nick)){
            nick=user;
        }
        if (StringUtil.isEmpty(user)||
                StringUtil.isEmpty(avatar)||
                StringUtil.isEmpty(password)||
                StringUtil.isEmpty(email)||
                StringUtil.isEmpty(phone)){
            return new ApiResult(false,Massages.MISS_ARGS.toString(),null);
        }
        if (!StringUtil.validMail(email)||!StringUtil.validPhone(phone)){
            return new ApiResult(false,Massages.INVALID_FORMAT.toString(),null);
        }
        if (service.isUserNameOccupied(user)){
            return new ApiResult(false,Massages.USER_EXISTS.toString(),null);
        }
        User usr= new User();
        usr.setUserName(user);
        usr.setPassword(StringUtil.md5Encode(password,salt));
        usr.setAvatar(avatar);
        usr.setEmail(email);
        usr.setPhone(phone);
        usr.setSalt(salt);
        usr.setType(User.TYPE_STUDENT);
        usr.setNickName(nick);
        usr.setApplyTeacher(teacher);
        //调用业务方法，添加到数据库
        VmUser vmUser = VmUser.apiLogin(service.register(usr));
        return new ApiResult(true,Massages.SUCCESS.toString(),vmUser);
    }
    @Value("${user.pic}")
    private String path;
    @ApiOperation("文件上传")
    @ApiImplicitParam(name = "avatar",value = "文件",dataType = "MultipartFile",dataTypeClass = MultipartFile.class,
            paramType = "query",required = true)
    @PostMapping(ApiConstant.ROUTE_AUTH_UPLOAD)
    public ApiResult upload(@RequestParam("avatar")MultipartFile file){
        JSONObject result= FileUtil.uploadWithRandomName(file,path);
        return new ApiResult(result.getBoolean(FileUtil.UPLOAD_PARAM_STATUS),
                result.getString(FileUtil.UPLOAD_PARAM_MESSAGE),
                result.getString(FileUtil.UPLOAD_PARAM_URL));
    }
}
